package com.dng.book.controller;

import com.dng.book.util.RedisUtil;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class CaptchaController {
    @Autowired
    private DefaultKaptcha kaptcha;
    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/api/captcha")
    public Map<String, String> getCaptcha(@RequestParam String username) throws Exception {
        String code = kaptcha.createText();
        log.info("生成验证码: username={}, code={}", username, code);
        
        // 使用RedisUtil设置验证码
        String redisKey = "captcha:" + username;
        boolean setResult = redisUtil.set(redisKey, code, 5, TimeUnit.MINUTES);
        log.info("Redis设置验证码结果: key={}, value={}, result={}", redisKey, code, setResult);
        
        // 立即验证设置是否成功
        String check = redisUtil.get(redisKey);
        log.info("生成验证码后立即get: key={}, value={}", redisKey, check);
        
        // 检查所有captcha相关key
        java.util.Set<String> keys = redisUtil.keys("captcha:*");
        log.info("生成验证码后，当前Redis captcha相关key: {}", keys);
        
        // 测试Redis连接
        boolean connectionTest = redisUtil.testConnection();
        log.info("Redis连接测试结果: {}", connectionTest);
        
        BufferedImage image = kaptcha.createImage(code);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(image, "png", out);
        String img = "data:image/png;base64," + Base64.getEncoder().encodeToString(out.toByteArray());
        Map<String, String> result = new HashMap<>();
        result.put("img", img);
        return result;
    }

    /**
     * 方案1：单个验证码校验接口
     */
    @GetMapping("/api/captcha/verify")
    public Map<String, Object> verifyCaptcha(@RequestParam String username, @RequestParam String captchaCode) {
        Map<String, Object> result = new HashMap<>();
        String redisKey = "captcha:" + username;
        String realCode = redisUtil.get(redisKey);
        if (realCode == null) {
            result.put("valid", false);
            result.put("message", "验证码不存在或已过期");
            result.put("exists", false);
        } else if (realCode.equalsIgnoreCase(captchaCode)) {
            result.put("valid", true);
            result.put("message", "验证码正确");
            result.put("exists", true);
        } else {
            result.put("valid", false);
            result.put("message", "验证码错误");
            result.put("exists", true);
        }
        return result;
    }
} 